<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?a7c05ce530152d9866930ef4850ee566"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <title>java提高篇(三) 理解java的三大特性之多态 | 神奇的鸭鸭の码农库 | 新知识要不断的总结记录成笔记，要多写，多画，能够清晰透彻的将知识讲给别人听，才是达到理解的层次。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#765959">
    
    
    <meta name="keywords" content="java基础">
    <meta name="description" content="学习来源：http://cmsblogs.com 多态封装隐藏了他的内部实现机制，可以在不影响使用的情况下改变类的内部结构，同时也保护了数据。对外界他的实现细节是隐藏的，暴露给外界的只是他的访问方法。 继承是为了复用父类代码，两个类如果存在is-a的关系就可以使用继承。同时继承也为多态做了铺垫。那么多态是什么，多态的实现机制又是什么？下面会为你揭开： 不多态是指程序中定义的引用变量所指向的具体类型">
<meta name="keywords" content="java基础">
<meta property="og:type" content="article">
<meta property="og:title" content="java提高篇(三) 理解java的三大特性之多态">
<meta property="og:url" content="http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/index.html">
<meta property="og:site_name" content="神奇的鸭鸭の码农库">
<meta property="og:description" content="学习来源：http://cmsblogs.com 多态封装隐藏了他的内部实现机制，可以在不影响使用的情况下改变类的内部结构，同时也保护了数据。对外界他的实现细节是隐藏的，暴露给外界的只是他的访问方法。 继承是为了复用父类代码，两个类如果存在is-a的关系就可以使用继承。同时继承也为多态做了铺垫。那么多态是什么，多态的实现机制又是什么？下面会为你揭开： 不多态是指程序中定义的引用变量所指向的具体类型">
<meta property="og:updated_time" content="2017-12-05T09:56:25.750Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java提高篇(三) 理解java的三大特性之多态">
<meta name="twitter:description" content="学习来源：http://cmsblogs.com 多态封装隐藏了他的内部实现机制，可以在不影响使用的情况下改变类的内部结构，同时也保护了数据。对外界他的实现细节是隐藏的，暴露给外界的只是他的访问方法。 继承是为了复用父类代码，两个类如果存在is-a的关系就可以使用继承。同时继承也为多态做了铺垫。那么多态是什么，多态的实现机制又是什么？下面会为你揭开： 不多态是指程序中定义的引用变量所指向的具体类型">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">神奇的鸭鸭</h5>
          <a href="mailto:702038338@qq.com" title="702038338@qq.com" class="mail">702038338@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/magic_duck" target="_blank" >
                <i class="icon icon-lg icon-gg-circle"></i>
                码云
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.zhihu.com/people/shen-qi-de-ya-ya" target="_blank" >
                <i class="icon icon-lg icon-twitter"></i>
                知乎
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">java提高篇(三) 理解java的三大特性之多态</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">java提高篇(三) 理解java的三大特性之多态</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-10-23T02:03:00.000Z" itemprop="datePublished" class="page-time">
  2017-10-23
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#多态"><span class="post-toc-number">1.</span> <span class="post-toc-text">多态</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#多态的实现"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">多态的实现</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#基于继承实现的多态"><span class="post-toc-number">1.1.1.</span> <span class="post-toc-text">基于继承实现的多态</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#基于接口实现的多态"><span class="post-toc-number">1.1.2.</span> <span class="post-toc-text">基于接口实现的多态</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#经典实例"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">经典实例</span></a></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-java_enhance3_多态"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">java提高篇(三) 理解java的三大特性之多态</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年10月23日 10:03" datetime="2017-10-23T02:03:00.000Z"  itemprop="datePublished">2017-10-23</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>学习来源：<a href="http://cmsblogs.com" target="_blank" rel="external">http://cmsblogs.com</a></p>
<h2 id="多态"><a href="#多态" class="headerlink" title="多态"></a>多态</h2><p>封装隐藏了他的内部实现机制，可以在不影响使用的情况下改变类的内部结构，同时也保护了数据。对外界他的实现细节是隐藏的，暴露给外界的只是他的访问方法。</p>
<p>继承是为了复用父类代码，两个类如果存在is-a的关系就可以使用继承。同时继承也为多态做了铺垫。那么多态是什么，多态的实现机制又是什么？下面会为你揭开：<br> 不<br><strong>多态是指程序中定义的引用变量所指向的具体类型和通过该引用变量发出的方法调用在编程时并不确定，而是在程序运行时才确定，即一个变量到底会执行哪个类的示例对象，该引用变量发出的方法到底时执行那个类中实现的方法，必须在程序运行期间才能决定。因为程序在运行时才确定具体的类。这样不用修改源码，就能将引用变量绑定到各种不同的类实现上，从而导致该引用调用的具体方法随着而变，既不用修改代码就能改变程序运行时绑定的具体代码，让程序可以选择多种运行状态，这就是多态。</strong></p>
<p>比如你是一个酒神，对酒情有独钟。某日回家发现桌上有几个杯子里面都装了白酒，从外面看我们是不可能知道这是些什么酒，只有喝了之后才能够猜出来是何种酒。你一喝，这是剑南春、再喝这是五粮液、再喝这是酒鬼酒….在这里我们可以描述成如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">酒 a = 剑南春</div><div class="line">酒 b = 五粮液</div><div class="line">酒 c = 酒鬼酒</div></pre></td></tr></table></figure></p>
<p>这里所表现的的就是多态。剑南春、五粮液、酒鬼酒都是酒的子类，我们只是通过酒这一个父类就能够引用不同的子类，这就是多态——<strong>我们只有在运行的时候才知道引用变量指向的具体示例对象。</strong></p>
<p>讲到多态就不可不提向上转型，在上面的喝酒例子中：酒（Wine）是父类，剑南春（JNC）、五粮液（WLY）、酒鬼酒（JGJ）是子类。我们定义如下代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Wine a = <span class="keyword">new</span> JNC();</div></pre></td></tr></table></figure></p>
<p>这种做存在一个非常大的好处，在继承中我们知道子类是父类的扩展，它可以提供比父类更强大的功能，如果我们定义了一个指向子类的父类类型，那么它除了能引用父类的共性之外，还能使用子类的强大功能。</p>
<p>但是向上转型有一些缺陷，那就是它比如导致某些方法和属性的丢失，导致我们无法获取他们。所以父类的引用可以调用父类中定义的所有属性和方法，对于只存在于子类的属性和方法就望尘莫及了。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Wine</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun1</span><span class="params">()</span></span>&#123;</div><div class="line">        System.out.println(<span class="string">"Wine 的Fun....."</span>);</div><div class="line">        fun2();</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun2</span><span class="params">()</span></span>&#123;</div><div class="line">        System.out.println(<span class="string">"Wine 的Fun2..."</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JNC</span> <span class="keyword">extends</span> <span class="title">Wine</span></span>&#123;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * <span class="doctag">@desc</span> 子类重载父类方法 父类中不存在该方法，向上转型后，父类是不能引用该方法的</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> a</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun1</span><span class="params">(String a)</span></span>&#123;</div><div class="line">        System.out.println(<span class="string">"JNC 的 Fun1..."</span>);</div><div class="line">        fun2();</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 子类重写父类方法</span></div><div class="line"><span class="comment">     * 指向子类的父类引用调用fun2时，必定是调用该方法</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun2</span><span class="params">()</span></span>&#123;</div><div class="line">        System.out.println(<span class="string">"JNC 的Fun2..."</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">        Wine a = <span class="keyword">new</span> JNC();</div><div class="line">        a.fun1();</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">-------------------------------------------------</div><div class="line">Output:</div><div class="line">Wine 的Fun.....</div><div class="line">JNC 的Fun2...</div></pre></td></tr></table></figure></p>
<p>综合上述，我们可以总结如下：<strong>指向子类的父类引用由于向上转型了，它只能访问父类中的属性和方法，而对于子类中存在父类中不存在的方法，该引用是不能使用的，尽管是重载该方法。若子类重写了父类中的某些方法，在调用该方法的时候，必定是使用子类中定义的方法(动态连接，动态调用)</strong></p>
<p>对于面向对象而言，多态分为编译时多态和运行时多态。其中编译时多态是静态的，主要是方法的重载，他是根据参数列表来区分不同的函数，通过编译后会变成两个不同的函数，在运行时谈不上多态。而运行时多态是动态的，他是通过动态绑定的，也就是我们常说的多态性。</p>
<h3 id="多态的实现"><a href="#多态的实现" class="headerlink" title="多态的实现"></a>多态的实现</h3><p>Java实现多态有三个必要条件：<strong>继承，重写，向上转型</strong>。只有满足了这三个条件，我们才能够在同一个继承结构中使用统一的逻辑实现代码处理不同的对象，从而达到执行不同的行为。</p>
<p>在Java中有两种形式可以实现多态。继承和接口。</p>
<h4 id="基于继承实现的多态"><a href="#基于继承实现的多态" class="headerlink" title="基于继承实现的多态"></a>基于继承实现的多态</h4><p>基于继承的实现机制主要表现在父类和继承该父类的一个或多个子类对某些方法的重写，多个子类对同一方法的重写可以表现出不同的行为：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Wine</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> String name;</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> name;</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.name = name;</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Wine</span><span class="params">()</span></span>&#123;</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">drink</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"喝的是 "</span> + getName();</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 重写toString()</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JNC</span> <span class="keyword">extends</span> <span class="title">Wine</span></span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">JNC</span><span class="params">()</span></span>&#123;</div><div class="line">        setName(<span class="string">"JNC"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 重写父类方法，实现多态</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">drink</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"喝的是 "</span> + getName();</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 重写toString()</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"Wine : "</span> + getName();</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JGJ</span> <span class="keyword">extends</span> <span class="title">Wine</span></span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">JGJ</span><span class="params">()</span></span>&#123;</div><div class="line">        setName(<span class="string">"JGJ"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 重写父类方法，实现多态</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">drink</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"喝的是 "</span> + getName();</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 重写toString()</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"Wine : "</span> + getName();</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">        <span class="comment">//定义父类数组</span></div><div class="line">        Wine[] wines = <span class="keyword">new</span> Wine[<span class="number">2</span>];</div><div class="line">        <span class="comment">//定义两个子类</span></div><div class="line">        JNC jnc = <span class="keyword">new</span> JNC();</div><div class="line">        JGJ jgj = <span class="keyword">new</span> JGJ();</div><div class="line">        <span class="comment">//父类引用子类对象</span></div><div class="line">        wines[<span class="number">0</span>] = jnc;</div><div class="line">        wines[<span class="number">1</span>] = jgj;</div><div class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span> ; i &lt; <span class="number">2</span> ; i++)&#123;</div><div class="line">            System.out.println(wines[i].toString() + <span class="string">"--"</span> + wines[i].drink());</div><div class="line">        &#125;</div><div class="line">        System.out.println(<span class="string">"-------------------------------"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">OUTPUT:</div><div class="line">Wine : JNC--喝的是 JNC</div><div class="line">Wine : JGJ--喝的是 JGJ</div><div class="line">-------------------------------</div></pre></td></tr></table></figure></p>
<p>在上面的代码中JNC、JGJ继承Wine，并且重写了drink()、toString()方法，程序运行结果是调用子类中方法，输出JNC、JGJ的名称，这就是多态的表现。不同的对象可以执行相同的行为，但是他们都需要通过自己的实现方式来执行，这就要得益于向上转型了。</p>
<p>Object、Wine、JGJ三者继承链关系是：JGJ—&gt;Wine—&gt;Object。所以我们可以这样说：<strong>当子类重写父类的方法被调用时，只有对象继承链中的最末端的方法才会被调用。</strong>但是注意如果这样写：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Object o = <span class="keyword">new</span> Wine();</div><div class="line">System.out.println(o.toString()); <span class="comment">//null 因为Wine不在该对象的继承链中。</span></div></pre></td></tr></table></figure></p>
<p>对于引用子类的父类类型，在处理该引用时，它适用于继承该父类的所有子类，子类对象的不同，对方法的实现也就不同，执行相同动作产生的行为也就不同。</p>
<h4 id="基于接口实现的多态"><a href="#基于接口实现的多态" class="headerlink" title="基于接口实现的多态"></a>基于接口实现的多态</h4><p>在接口多态中，指向接口引用的必须是实现了这个接口的一个类的示例对象。但是接口可以是多继承多实现，它能够利用一组相关或者不相关的接口进行组合与扩充，能够对外提供一致的服务接口。所以它相对于继承来说有更好的灵活性。</p>
<h3 id="经典实例"><a href="#经典实例" class="headerlink" title="经典实例"></a>经典实例</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">show</span><span class="params">(D obj)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> (<span class="string">"A and D"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">show</span><span class="params">(A obj)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> (<span class="string">"A and A"</span>);</div><div class="line">    &#125; </div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span></span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">show</span><span class="params">(B obj)</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> (<span class="string">"B and B"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">show</span><span class="params">(A obj)</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> (<span class="string">"B and A"</span>);</div><div class="line">    &#125; </div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">C</span> <span class="keyword">extends</span> <span class="title">B</span></span>&#123;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">D</span> <span class="keyword">extends</span> <span class="title">B</span></span>&#123;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">        A a1 = <span class="keyword">new</span> A();</div><div class="line">        A a2 = <span class="keyword">new</span> B();</div><div class="line">        B b = <span class="keyword">new</span> B();</div><div class="line">        C c = <span class="keyword">new</span> C();</div><div class="line">        D d = <span class="keyword">new</span> D();</div><div class="line">        </div><div class="line">        System.out.println(<span class="string">"1--"</span> + a1.show(b));</div><div class="line">        System.out.println(<span class="string">"2--"</span> + a1.show(c));</div><div class="line">        System.out.println(<span class="string">"3--"</span> + a1.show(d));</div><div class="line">        System.out.println(<span class="string">"4--"</span> + a2.show(b));</div><div class="line">        System.out.println(<span class="string">"5--"</span> + a2.show(c));</div><div class="line">        System.out.println(<span class="string">"6--"</span> + a2.show(d));</div><div class="line">        System.out.println(<span class="string">"7--"</span> + b.show(b));</div><div class="line">        System.out.println(<span class="string">"8--"</span> + b.show(c));</div><div class="line">        System.out.println(<span class="string">"9--"</span> + b.show(d));      </div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>运行结果：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="number">1</span>--A and A</div><div class="line"><span class="number">2</span>--A and A</div><div class="line"><span class="number">3</span>--A and D</div><div class="line"><span class="number">4</span>--B and A</div><div class="line"><span class="number">5</span>--B and A</div><div class="line"><span class="number">6</span>--A and D</div><div class="line"><span class="number">7</span>--B and B</div><div class="line"><span class="number">8</span>--B and B</div><div class="line"><span class="number">9</span>--A and D</div></pre></td></tr></table></figure></p>
<p>前三个输出都非常简单，对于第四个输出来说，为什么不是输出”B and B”呢？因为被调用的这个方法必须是在超类中定义过的，也就是调用了子类重写的show(A obj)方法。其实在继承链中对象的方法调用存在一个优先级关系：<strong>this.show(O) – super.show(O) – this.show((super)O) – super.show((super)O)</strong></p>
<p>顺着这个关系我们分析第五个输出，a2.show(c)中，a2是A的引用变量，所以this代表A，首先会在A类中找这个方法，没有找到，于是到A的超类去找，找不到。所以调到第三级this.show((super)O)，C的超类有B,A。this同样是A，这里在A中找到了show(A obj),同时a2是B类的引用且重写了show(A obj)这个方法，因此最终会调用B类中的show(A obj)方法，结果也就是B and A。其他结果也可以用同样的方法确定。</p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-12-05T09:56:25.750Z" itemprop="dateUpdated">2017年12月5日 17:56</time>
</span><br>


        如要转载请注明出处：<a href="/2017/10/23/java_enhance3_多态/" target="_blank" rel="external">http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/</a>
    </div>
    <footer>
        <a href="http://magic_duck.oschina.io">
            <img src="/img/avatar.jpg" alt="神奇的鸭鸭">
            神奇的鸭鸭
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java基础/">java基础</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/&title=《java提高篇(三) 理解java的三大特性之多态》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/&title=《java提高篇(三) 理解java的三大特性之多态》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《java提高篇(三) 理解java的三大特性之多态》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/10/24/SSM/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">SSM框架执行流程</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/10/23/java_enhance2_继承/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">java提高篇(二) 理解java的三大特性之继承</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>神奇的鸭鸭の码农库 &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/&title=《java提高篇(三) 理解java的三大特性之多态》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/&title=《java提高篇(三) 理解java的三大特性之多态》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《java提高篇(三) 理解java的三大特性之多态》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://magic_duck.oschina.io/2017/10/23/java_enhance3_多态/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
